package com.vf.admin.client.controller;

import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dto.GuanZhuDto;
import com.vf.admin.client.service.AppFollowService;
import com.vf.admin.client.service.AppUserService;
import com.vf.admin.client.service.SystemAlertService;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.miaodong.entity.AppFollow;
import com.vf.admin.miaodong.entity.AppUser;
import com.vf.admin.utils.StringEx;
import com.vf.admin.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

import static com.vf.admin.common.Constants.guizuCacheMap;

/**
 * @author anxiang
 * @version 1.0.0
 * @ClassName AppGuanZhuAndFenSiController.java
 * @Description 用户关注与粉丝 操作接口
 * @createTime 2021年07月21日 11:20:00
 */

@Controller
@RequestMapping("/appguanzhuandfensi")
public class AppGuanZhuAndFenSiController extends ClientBaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AppFollowService appFollowService;
    @Autowired
    AppUserService appUserService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private AppDailyTasController dailyTasController;
    @Autowired
    private SystemAlertService systemAlertService;

    /*
     * @Description 关注和取消关注接口
     * @Param: usercode 操作的用户code
     * @Param: leixing 1关注 2取消关注
     * @return: com.vf.admin.common.entity.Result
     * @Author: ljx
     * @Date: 2021/07/21
     */
    @ResponseBody
    @RequestMapping("/guanzhu")
    public Result guanzhu(Integer userid, Integer leixing) {
        try {
            if (StringEx.isNull(userid)) {
                return this.errorJSON("用户不存在");
            }
            if (leixing == null) {
                return this.errorJSON("类型错误");
            }
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            //获取被操作的用户信息
            AppUser czuser = appUserService.getTcOrId(userid);
            if (StringUtils.isEmpty(czuser)) {
                return this.errorJSON("用户不存在");
            }
            //获取关注信息
            Map<String, Object> paramap = new HashMap<>(16);
            paramap.put("userid", czuser.getId());
            paramap.put("followeduserid", user.getId());
            List<AppFollow> appFollowList = appFollowService.findByList(paramap, null);
            //关注用户
            if (leixing == 1) {
                if (appFollowList == null || appFollowList.size() == 0) {
                    AppFollow appFollow = new AppFollow();
                    appFollow.setUserid(czuser.getId());//被关注人用户id
                    appFollow.setBgzusercode(czuser.getUsercode());//被关注人用户账号
                    appFollow.setBgzphone(czuser.getLoginname());//被关注人手机号
                    appFollow.setBgznick(czuser.getNick());//被关注人名称
                    appFollow.setBgzpic(czuser.getPic());//被关注人头像
                    appFollow.setBgzgrade("0");//被关注人等级
                    appFollow.setBgzsex(czuser.getSex());//被关注人性别
                    if (StringEx.isNotNull(czuser.getMysign())) {
                        appFollow.setBgzmysign(czuser.getMysign());//被关注签名
                    } else {
                        appFollow.setBgzmysign("");//被关注签名
                    }
                    appFollow.setFolloweduserid(user.getId());//关注人id
                    appFollow.setFollowedusercode(user.getUsercode());//关注人用户账号
                    appFollow.setFollowednick(user.getNick());//关注人的昵称
                    appFollow.setFollowedpic(user.getPic());//关注的头像
                    appFollow.setFollowedphone(user.getLoginname());//关注人的手机号
                    appFollow.setFollowedgrade("0");//关注人的等级
                    appFollow.setFollowedsex(user.getSex());//关注人性别
                    if (StringEx.isNotNull(user.getMysign())) {
                        appFollow.setFollowedmysign(user.getMysign());//关注人签名
                    } else {
                        appFollow.setFollowedmysign("");//关注人签名
                    }
                    appFollow.setStatus(1);//关注状态 1关注  2取消关注
                    appFollow.setUpdatetime(new Date());
                    appFollow.setCreatetime(appFollow.getUpdatetime());
                    appFollowService.save(appFollow);
                    //修改用户关注总数
                    appUserService.guanzhuUpdate(user.getId(), 1);
                    //修改被关注用户粉丝总数
                    appUserService.fansnumallUpdate(czuser.getId(), 1);
                    //修改被关注用户新增粉丝数
                    appUserService.fensiNewUpdate(czuser.getId());
                    //给被关注用户发送系统通知
                    systemAlertService.sendNEW_FANS(czuser.getTengxuncode(), user.getNick());
                } else {
                    //获取已经存在的数据
                    AppFollow appFollow = appFollowList.get(0);
                    //判断之前数据的状态
                    if (appFollow.getStatus().intValue() == 1) {
                        return this.errorJSON("已关注");
                    } else {
                        appFollow.setUpdatetime(new Date());
                        appFollow.setStatus(1);
                        appFollowService.save(appFollow);
                        //给被关注用户发送系统通知
                        systemAlertService.sendNEW_FANS(czuser.getTengxuncode(), user.getNick());
                    }
                }
                //完成日常任务
                dailyTasController.getAwardFocusOnce(userId, ClientConstants.TaskOnce.FOCUS_USER);
            } else if (leixing == 2) {//取消关注
                if (appFollowList == null || appFollowList.size() == 0) {
                    return this.errorJSON("已取消关注");
                } else {
                    //获取已经存在的数据
                    AppFollow appFollow = appFollowList.get(0);
                    if (appFollow.getStatus().intValue() == 1) {
                        appFollowService.del(appFollow.getId());
                        //修改用户关注总数
                        appUserService.guanzhuUpdate(user.getId(), 2);
                        //修改被关注用户粉丝总数
                        appUserService.fansnumallUpdate(appFollow.getUserid(), 2);
                    } else {
                        return this.errorJSON("关注失败");
                    }
                }
            } else {
                return this.errorJSON("类型错误");
            }
            return this.sucessJSON("成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("关注和取消关注接口异常" + e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

    /*
     * @Description 获取关注列表
     * @Param: pageno 获取页数
     * @return: com.vf.admin.common.entity.Result
     * @Author: ljx
     * @Date: 2021/10/22
     */
    @ResponseBody
    @RequestMapping("/guanzhulist")
    public Result guanzhulist(Integer pageno) {
        try {
            if (pageno == null) {
                return this.errorJSON("参数错误");
            }
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            //分页数据
            SplitPageBean splitPageBean = new SplitPageBean(pageno, 10);
            Map<String, Object> map = new HashMap<>(16);
            map.put("followeduserid", user.getId());
            List<AppFollow> appFollowList = appFollowService.findByList(map, splitPageBean);
            //返回数据
            List<GuanZhuDto> guanZhuDtoList = new ArrayList<>();
            if (appFollowList != null && appFollowList.size() > 0) {
                for (AppFollow appFollow : appFollowList) {
                    GuanZhuDto guanZhuDto = new GuanZhuDto();
                    guanZhuDto.setUserid(appFollow.getUserid());
                    guanZhuDto.setUsercode(appFollow.getBgzusercode());//用户标识
                    guanZhuDto.setUsericon(appFollow.getBgzpic());//用户头像
                    guanZhuDto.setUsernick(appFollow.getBgznick());//用户昵称
                    guanZhuDto.setUsersex(appFollow.getBgzsex());//用户性别
                    guanZhuDto.setQianming(appFollow.getBgzmysign());//用户签名

                    AppUser followUser = appUserService.get(appFollow.getUserid());
                    if (followUser.getIsguizu() == 1) {
                        String medal = guizuCacheMap.get(followUser.getNobleid());
                        guanZhuDto.setMedal(medal);
                    } else {
                        guanZhuDto.setMedal("");
                    }
                    if(followUser.getVipEndDate() != null) {
                        guanZhuDto.setIsVip(TimeUtils.afterNow(followUser.getVipEndDate())? 1: 0);
                    }
                    guanZhuDtoList.add(guanZhuDto);
                }
            }
            return this.sucessPage(guanZhuDtoList, splitPageBean.getNextPageNo());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("获取关注列表接口异常" + e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }

    }

    /**
     * 获取好友列表，互相关注极为好友
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/friends")
    public Result friends() {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            List<GuanZhuDto> friendsNumber = getFriendsNumber(userId);
            return this.sucessJSON(friendsNumber, "成功");
        } catch (Exception e) {
            e.printStackTrace();
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
     * 计算好友人数
     *
     * @param userId
     * @return
     */
    public List<GuanZhuDto> getFriendsNumber(Integer userId) {
        ArrayList<Integer> friends = getFriends(userId);
        List<GuanZhuDto> list = new ArrayList<>();
        for (Integer id : friends) {
            GuanZhuDto guanZhuDto = new GuanZhuDto();
            AppUser appUser = appUserService.get(id);
            guanZhuDto.setUserid(appUser.getId());
            guanZhuDto.setUsercode(appUser.getUsercode());
            guanZhuDto.setTengxuncode(appUser.getTengxuncode());
            guanZhuDto.setUsericon(appUser.getPic());
            guanZhuDto.setUsernick(appUser.getNick());
            guanZhuDto.setUsersex(appUser.getSex());
            guanZhuDto.setQianming(appUser.getMysign());
            guanZhuDto.setMedal("");
            if (appUser.getIsguizu() == 1) {
                String medal = guizuCacheMap.get(appUser.getNobleid());
                guanZhuDto.setMedal(medal);
            }
            if(appUser.getVipEndDate() != null) {
                guanZhuDto.setIsVip(TimeUtils.afterNow(appUser.getVipEndDate())? 1: 0);
            }
            list.add(guanZhuDto);
        }
        return list;
    }


    /**
     * 获取互相关注的IDS
     *
     * @param userId
     * @return
     */
    public ArrayList<Integer> getFriends(Integer userId) {
        ArrayList<Integer> objects = new ArrayList<>();
        //关注人列表
        Map<String, Object> map = new HashMap<>();
        map.put("followeduserid", userId);
        List<AppFollow> listOne = appFollowService.findByListAll(map);
        //粉丝列表
        Map<String, Object> tmap = new HashMap<>();
        tmap.put("userid", userId);
        List<AppFollow> listTwo = appFollowService.findByListAll(tmap);
        if (Objects.isNull(listOne) || Objects.isNull(listTwo)) return objects;
        listOne.forEach(e -> {
            listTwo.forEach(s -> {
                if (s.getUserid().equals(e.getFolloweduserid()) && s.getFolloweduserid().equals(e.getUserid())) {
                    objects.add(e.getUserid());
                }
            });
        });
        return objects;
    }

    /**
     * @Description 获取粉丝列表
     * @Param: [pageno]
     * @return: com.vf.admin.common.entity.Result
     * @Author: ljx
     * @Date: 2021/10/22
     */
    @ResponseBody
    @RequestMapping("/fensilsit")
    public Result fensilsit(Integer pageno) {
        try {
            if (pageno == null) {
                return this.errorJSON("参数错误");
            }
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            //分页数据
            SplitPageBean splitPageBean = new SplitPageBean(pageno, 10);
            Map<String, Object> map = new HashMap<>(16);
            map.put("userid", user.getId());
            List<AppFollow> appFollowList = appFollowService.findByList(map, splitPageBean);
            //清空新增粉丝数
            appUserService.fensiNewClear(user.getId());
            //返回数据
            List<GuanZhuDto> guanZhuDtoList = new ArrayList<>();
            if (appFollowList != null && appFollowList.size() > 0) {
                for (AppFollow appFollow : appFollowList) {
                    GuanZhuDto guanZhuDto = new GuanZhuDto();
                    guanZhuDto.setUserid(appFollow.getFolloweduserid());
                    guanZhuDto.setUsercode(appFollow.getFollowedusercode());//用户标识
                    guanZhuDto.setUsericon(appFollow.getFollowedpic());//用户头像
                    guanZhuDto.setUsernick(appFollow.getFollowednick());//用户昵称
                    guanZhuDto.setUsersex(appFollow.getFollowedsex());//用户性别
                    guanZhuDto.setQianming(appFollow.getFollowedmysign());//用户签名
                    //是否互相关注
                    AppFollow appFollow1 = appFollowService.getFollew(userId, appFollow.getFolloweduserid());
                    if (appFollow1 != null) {
                        guanZhuDto.setGuanzhu(true);
                    } else {
                        guanZhuDto.setGuanzhu(false);
                    }

                    AppUser followUser = appUserService.get(appFollow.getFolloweduserid());
                    if (followUser.getIsguizu() == 1) {
                        String medal = guizuCacheMap.get(followUser.getNobleid());
                        guanZhuDto.setMedal(medal);
                    } else {
                        guanZhuDto.setMedal("");
                    }
                    if(followUser.getVipEndDate() != null) {
                        guanZhuDto.setIsVip(TimeUtils.afterNow(followUser.getVipEndDate())? 1: 0);
                    }
                    guanZhuDtoList.add(guanZhuDto);
                }
            }
            return this.sucessPage(guanZhuDtoList, splitPageBean.getNextPageNo());
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("获取列表列表接口异常" + e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }


}
